<template>
  <div class="member-container">
    <div class="member-package">
      <!-- 权益介绍 -->
      <rightsV1 :packageType="packageType" v-if="packageType" />

      <!-- 支付 -->
      <div class="member-wrap">
        <div
          class="product-nav"
          :class="[packageType, 'leng' + showTypeArr.length]"
        >
          <div
            class="product-nav-item"
            :class="'item-' + it"
            @click="packageType = it"
            v-report="it==='vip'?62:63"
            v-for="it in showTypeArr"
            :key="it"
          >
            <span v-if="it === 'vip'">会员</span>
            <span v-else>翻译币加购包</span>
          </div>
          <div class="product-nav-bg" />
        </div>

        <div class="member-cont">
          <div class="member-cont_">
            <div class="product-swiper" v-show="packageType === 'vip'">
              <div class="swiper-container" ref="productSwiperRef">
                <div class="swiper-wrapper">
                  <div
                    class="swiper-slide"
                    style="width: auto"
                    v-for="(item, i) in products"
                    :key="item.id"
                  >
                    <div
                      class="time-item"
                      :class="{
                        checked: selectedVip.id === item.id
                      }"
                      @click="setVipItem(item, i)"
                      :style="productTimeItemStyle"
                    >
                      <div
                        class="custom-tag"
                        v-if="productTagMap[item.id]"
                        :style="{
                          'background-image': `url('${productTagMap[item.id]}')`
                        }"
                      />

                      <div class="item-cont">
                        <div class="item-name" v-if="item.cycle_pay_flag">
                          {{ item.name }}
                        </div>
                        <div class="item-name" v-else>
                          {{ item.extText }}
                        </div>

                        <div class="price">
                          <span class="mark2">{{ moneySymbol }}</span
                          >{{ item._actPrice }}
                        </div>
                        <span class="origin-price" v-if="!item.cycle_pay_flag"
                          >{{ moneySymbol }}{{ item._origin_price }}</span
                        >
                        <div class="monthly-price" v-if="item.productDecs">
                          {{ item.productDecs }}
                        </div>
                        <div v-else />
                      </div>
                      <div style="height: 10px" v-if="!hasCouponPrice" />
                      <div class="upper-coupon" v-else-if="item._coupon_price">
                        <em
                          >优惠券最高抵扣{{ moneySymbol
                          }}{{ item._coupon_price }}</em
                        >
                      </div>
                      <div class="upper-coupon" style="opacity: 0" v-else />
                    </div>
                  </div>
                </div>
                <div v-if="!products.length" class="empty-status">
                  新套餐即将上架，敬请期待！
                </div>
              </div>
              <div class="product ps-swiper-prev">
                <svg-icon iconClass="right" />
              </div>
              <div class="product ps-swiper-next">
                <svg-icon iconClass="right" />
              </div>
            </div>

            <div class="product-swiper" v-show="packageType === 'extra'">
              <div class="swiper-container" ref="extraSwiperRef">
                <div class="swiper-wrapper">
                  <div
                    class="swiper-slide"
                    style="width: auto"
                    v-for="(item, i) in extraList"
                    :key="item.id"
                  >
                    <div
                      class="time-item"
                      :class="{
                        checked: selectedExtra.id === item.id
                      }"
                      @click="setExtraItem(item, i)"
                      :style="extraListTimeItemStyle"
                    >
                      <div
                        class="custom-tag"
                        v-if="productTagMap[item.id]"
                        :style="{
                          'background-image': `url('${productTagMap[item.id]}')`
                        }"
                      />

                      <div class="give top">
                        <em>{{ item.extraName }}</em>
                      </div>

                      <div class="item-cont">
                        <div class="price">
                          <span class="mark2">{{ moneySymbol }}</span
                          >{{ item._actPrice }}
                        </div>
                        <span class="origin-price">
                          <template v-if="!item.cycle_pay_flag">
                            {{ moneySymbol }}{{ item._origin_price }}
                          </template>
                        </span>
                        <div
                          class="monthly-price"
                          :style="extraListMonthlyPriceStyle"
                        >
                          {{ item.extraDecs }}
                        </div>

                        <div class="time">-- {{ item.extraTime }} --</div>
                      </div>
                    </div>
                  </div>
                </div>
                <div v-if="!extraList.length" class="empty-status">
                  新套餐即将上架，敬请期待！
                </div>
              </div>
              <div class="extra ps-swiper-prev">
                <svg-icon iconClass="right" />
              </div>
              <div class="extra ps-swiper-next">
                <svg-icon iconClass="right" />
              </div>
            </div>

            <template v-if="showVipCoupon">
              <CouponList
                v-show="vipCouponList.length"
                ref="couponListRef"
                class="mt5"
                :price="selectedProduct._actPrice"
                :unit="moneySymbol"
                v-model:data="vipCouponList"
                @couponChange="couponChange"
                @selectProductByCoupon="selectProductByCoupon"
                @canRefreshCouponByCoupon="canRefreshCouponByCoupon"
              />
            </template>

            <div class="member-order mt10" v-show="selectedProduct.id">
              <div class="detail-wrap">
                <div class="pay-way">
                  <PaymentCode v-if="isDefaultMerchant"
                    ref="payCodeRef"
                    :product="selectedProduct"
                    class="pay-code-wrap"
                    :hasLogin="hasLogin"
                    :width="codeSize.width"
                    :height="codeSize.height"
                    :padding="codeSize.padding"
                    :otherParamsStr="otherParamsStr"
                    @login="openLogin"
                    @onStatusChange="onPayChange"
                  />
                  <PaymentCodeSll v-else-if="isSllMerchant"
                    ref="payCodeRef"
                    :product="selectedProduct"
                    class="pay-code-wrap"
                    :hasLogin="hasLogin"
                    :width="codeSize.width"
                    :height="codeSize.height"
                    :padding="codeSize.padding"
                    :otherParamsStr="otherParamsStr"
                    @login="openLogin"
                    @onStatusChange="onPayChange"
                  />
                  <PaymentCodeLx v-else-if="isLxMerchant"
                    ref="payCodeRef"
                    :product="selectedProduct"
                    class="pay-code-wrap"
                    :hasLogin="hasLogin"
                    :width="codeSize.width"
                    :height="codeSize.height"
                    :padding="codeSize.padding"
                    :otherParamsStr="otherParamsStr"
                    @login="openLogin"
                    @onStatusChange="onPayChange"
                  />
                  <p class="mt10 fs12">
                    支持：<template v-if="!selectedProduct.cycle_pay_flag"
                      ><svg-icon
                        style="color: #31a531"
                        iconClass="wechat-pay"
                      />微信 /</template
                    ><svg-icon
                      style="color: #4285f4"
                      iconClass="alipay"
                    />支付宝
                  </p>
                </div>

                <div class="pay-money">
                  <div class="flex-center actually-paid">
                    <span class="total-money">实付：</span>
                    <span class="price" v-if="selectedProduct.id">
                      <span class="mark2">{{ moneySymbol }}</span>
                      <countUp
                        :end-val="actualMoney"
                        :start-val="selectedProduct._origin_price"
                        :decimalPlaces="actualMoneyDecimalPlaces"
                        :duration="0.5"
                      />
                      <span class="save-money"
                        >立省<countUp
                          :end-val="saveMoney"
                          :decimalPlaces="saveMoneyDecimalPlaces"
                          :duration="0.5"
                      /></span>
                    </span>
                    <span class="origin-price"
                      >原价:{{ selectedProduct._origin_price }}</span
                    >
                  </div>

                  <div class="agree-wrap">
                    <div
                      v-if="
                        selectedProduct.cycle_pay_flag &&
                        selectedProduct._next_cycle_pay_text
                      "
                    >
                      {{ selectedProduct._next_cycle_pay_text }}
                    </div>
                    <div>
                      <span
                        >开通前阅读并同意<a
                          @click.prevent="openLink(appCfg.vipProtocol)"
                          target="_blank"
                          class="agreement"
                          >《会员服务协议》</a
                        >
                        <a
                          v-show="selectedProduct.cycle_pay_flag"
                          @click.prevent="openLink(appCfg.cycleProtocol)"
                          target="_blank"
                          class="agreement"
                          >《自动续费规则》</a
                        ></span
                      >
                    </div>

                    <div v-show="!isLxMerchant && packageType === 'extra'">购买后不支持退款</div>

                    <div class="lx-sale-tip" v-if="isLxMerchant">
                      <svg-icon icon-class="sale-return" :size="16"/>
                      <span>支持7天无理由退款 </span>
                      <el-popover
                        trigger="hover"
                        effect="dark"
                        popper-class="return-question-pop"
                        placement="top"
                        width="400">
                        <div class="return-content">
                          满足7天无理由退款的前提下，可在联想应用商店，我的订单处申请退款，也可联系联想软件商店客服申请退款。
                        </div>
                        <template #reference>
                          <svg-icon icon-class="error" class-name="tip-icon" />
                        </template>
                      </el-popover>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 支付成功弹框 -->
    <PaySuccess v-model="paySuccessVisible" :type="paySuccessType" />

    <!-- 匿名登录支付成功弹框 -->
    <AnonymousSuccess v-model="anonymousPaySuccessVisible" :type="anonymousPaySuccessType"/>
  </div>
</template>
<script setup lang="ts" name="PayComp">
import { onMounted, watch, ref, computed, nextTick } from "vue";
import { storeToRefs } from "pinia";
import { systemAppStore } from "@/stores/system";
import { userAppStore } from "@/stores/user";
import { activityAppStore } from "@/stores/activity";
import { messageAppStore } from "@/stores/message";
import PsMessage from "@/components/message/index";
import { openLink } from "@/utils/costum-api";
import { formatMoney, formatTsb } from "@/utils/costum";
import { requestConfig } from "@/utils/costum-config";
import { getProducts, getExtraPackage } from "@/api/rights";
import PaymentCode from "@/components/payment-code/src/index.vue";
import PaymentCodeSll from '@/components/payment-code/src/payment-code-sll.vue'
import PaymentCodeLx from '@/components/payment-code/src/payment-code-lx.vue'
import rightsV1 from "./components/rights-v1.vue";
import PaySuccess from "./components/success.vue";
import AnonymousSuccess from './components/anonymous-success.vue'
import CouponList from "./components/coupon-list.vue";
import eventBus from '@/utils/mitt';
import "swiper/dist/css/swiper.css";
// @ts-ignore
import Swiper from "swiper/dist/js/swiper";
import countUp from "vue-countup-v3";
import { invokeAPi } from "@/xz-fn";
import { getLocalStorage, setLocalStorage } from "@/utils/storage";
const _systemAppStore_ = systemAppStore();
const _userAppStore_ = userAppStore();
const _activityAppStore_ = activityAppStore();
const _messageAppStore_ = messageAppStore();
const { hasLogin, userInfo } = storeToRefs(_userAppStore_);
const { appCfg, appInfo, showTsb } = storeToRefs(_systemAppStore_);
const { activityInfo, productActList } = storeToRefs(_activityAppStore_);
const { openPayTabNotice } = storeToRefs(_messageAppStore_);
const payCodeRef = ref<InstanceType<typeof PaymentCode> | null>(null);
const couponListRef = ref<InstanceType<typeof CouponList> | null>(null);
const productSwiperRef = ref(null);
const extraSwiperRef = ref(null);
// 会员套餐
const products = ref<any[]>([]);
const selectedVip = ref<any>({});
// 支付成功弹框
const paySuccessVisible = ref(false);
const paySuccessType = ref("");
// 匿名登录支付成功弹窗
const anonymousPaySuccessVisible = ref(false)
const anonymousPaySuccessType = ref('')
// 商品热门标签
const productTagMap = ref<any>({});
const vipCurCoupon = ref({
  coupon_id: 0,
  amount: 0
});

const vipListLoaded = ref(false);
const extraListLoaded = ref(false);
// 套餐类型
const packageType = ref("");

// 翻译币套餐
const extraList = ref<any[]>([]);
const selectedExtra = ref<any>({});

const productTimeItemStyle = ref<any>({});
const extraListTimeItemStyle = ref<any>({});
const extraListMonthlyPriceStyle = ref<any>({});
//  vip 可用券列表
const vipCouponList = ref<any[]>([]);

let timer2: number | null, $productSwiper: any, $extraSwiper: any

const actByProductMap = computed<any>(() => {
  const o: any = {};
  for (const pInfo of products.value) {
    for (const actInfo of productActList.value) {
      if (actInfo.product_ids.includes(pInfo.id)) {
        o[pInfo.id] = actInfo;
        break;
      }
    }
  }
  return o;
});

const productActInfo = computed<any>(() => {
  return actByProductMap.value[selectedProduct.value.id] || activityInfo.value || {}
});
const otherParamsStr = computed(() => {
  const obj: any = {};
  if (
    productActInfo.value.id &&
    !["10003"].includes(productActInfo.value.act_fixed_id)
  ) {
    // 10003 为普通活动，仅显示
    obj["actid"] = productActInfo.value.id;
  }
  if (selectedProduct.value.cycle_pay_flag) {
    obj["paywayops"] = [1];
  }
  if (curCoupon.value.coupon_id) {
    obj["couponid"] = curCoupon.value.coupon_id;
  }
  return JSON.stringify(obj);
});
const moneySymbol = computed(() => {
  return "￥";
});


const codeSize = computed(() => {
  return isLxMerchant.value ? {
    height: 110,
    width: 110,
    padding: 5
  } : {
    height: 130,
    width: 130,
    padding: 6
  };
});
// 当前商品-实际付款价格
const actualMoney = computed(() => {
  return (
    formatActPrice(
      selectedProduct.value,
      actByProductMap.value[selectedProduct.value.id],
      userInfo.value.has_buy,
      curCoupon.value.amount
    ) || 0.01
  );
});
const actualMoneyDecimalPlaces = computed(() => {
  return ((actualMoney.value + "").split(".")[1] || "").length;
});
// 当前商品-实际付款优惠金额
const saveMoney = computed(() => {
  const originMoney = selectedProduct.value.origin_price;
  const curMoney = actualMoney.value * 100;
  const dis = Math.max(0, originMoney - curMoney);
  const result = dis / 100;
  const str = String(dis / 100);
  const dotIndex = str.indexOf(".");
  if (dotIndex !== -1) {
    return Number(
      `${str.slice(0, dotIndex)}.${str.slice(dotIndex + 1, dotIndex + 3)}`
    );
  } else {
    return Number(result);
  }
});

// 支付方式
const isDefaultMerchant = computed(() => appInfo.value.merchant === '')
const isSllMerchant = computed(() => appInfo.value.merchant === '360')
const isLxMerchant = computed(() => appInfo.value.merchant === 'lx')

const saveMoneyDecimalPlaces = computed(() => {
  return ((saveMoney.value + "").split(".")[1] || "").length;
});
const selectedProduct = computed<any>(() => {
  if (packageType.value === "vip") {
    return selectedVip.value;
  }
  if (packageType.value === "extra") {
    return selectedExtra.value;
  }
  return {};
});
const curCoupon = computed(() => {
  if (packageType.value === "vip") {
    return vipCurCoupon.value;
  } else {
    return {
      coupon_id: 0,
      amount: 0
    };
  }
});
const showTypeArr = computed(() => {
  return showTsb.value ? ["vip", "extra"] : ['vip'];
});
// 是否显示优惠券
const showVipCoupon = computed(() => {
  return packageType.value === "vip" && showTypeArr.value.includes("vip");
});
// 是否有优惠券
const hasCouponPrice = computed(() => {
  return products.value.some((it) => it._coupon_price);
});

watch(showTypeArr, () => {
  selectPackageType(packageType.value);
});
watch(openPayTabNotice, ({ tab }) => {
  if (tab === "tsb") {
    tab = "extra";
  } else if (!tab) {
    tab = "vip";
  }
  if (showTypeArr.value.includes(tab)) {
    packageType.value = tab;
  }
});

watch(hasLogin, () => {
  selectedVip.value = {};
  selectedExtra.value = {};
  products.value = [];
  productTagMap.value = {};
  if (packageType.value === "vip") {
    extraListLoaded.value = false;
    getPackage();
  } else if (packageType.value === "extra") {
    vipListLoaded.value = false;
    getExtraPackageList();
  }
  getProductTags();
});

watch(() => products.value.length, (val) => {
  setTimeItemStyle("vip");
  nextTick(() => {
    $productSwiper?.update();
  });
});
watch(() => extraList.value.length, (val) => {
  setTimeItemStyle("extra");
  nextTick(() => {
    $extraSwiper?.update();
  });
});
watch(packageType, (val) => {
  if (val === "vip") {
    !vipListLoaded.value && getPackage();
  } else if (val === "extra") {
    !extraListLoaded.value && getExtraPackageList();
  }
  nextTick(() => {
    if (val === "vip") {
      $productSwiper?.update();
    } else if (val === "extra") {
      $extraSwiper?.update();
    }
  });
});
onMounted(() => {
  selectPackageType(openPayTabNotice.value.tab);

  getProductTags();
  
  $productSwiper = new Swiper(productSwiperRef.value, {
    slidesPerView: "auto",
    spaceBetween: 8,
    navigation: {
      nextEl: ".product.ps-swiper-next",
      prevEl: ".product.ps-swiper-prev"
    }
  });
  $extraSwiper = new Swiper(extraSwiperRef.value, {
    slidesPerView: "auto",
    spaceBetween: 8,
    navigation: {
      nextEl: ".extra.ps-swiper-next",
      prevEl: ".extra.ps-swiper-prev"
    }
  });

});

function formatActPrice(
  productInfo: any,
  actInfo: any,
  has_buy: boolean,
  amount: number = 0,
  returnPrice: boolean = false
) {
  const { new_user_price, old_user_price, act_fixed_id } = actInfo || {};
  let { price } = productInfo || {};
  if (actInfo && ["10004"].includes(act_fixed_id)) {
    price = has_buy ? old_user_price : new_user_price;
  }
  if (amount) {
    price -= amount;
    if (price < 0) {
      price = 0;
    }
  }
  return returnPrice ? price : formatMoney(price);
}

function setTimeItemStyle(type: string) {
  const isVip = type === "vip";
  const len = isVip ? products.value.length : extraList.value.length;
  if (len >= 4) {
    if (!isVip) {
      extraListMonthlyPriceStyle.value = { "max-width": "130px" };
    }
    return;
  }

  const width = 640 / len - ((len - 1) * 8) / len + "px";

  if (isVip) {
    productTimeItemStyle.value = { width };
  } else {
    extraListTimeItemStyle.value = { width };
    extraListMonthlyPriceStyle.value = {};
  }
}
// 选择商品类型
function selectPackageType(tab: string) {
  if (tab === "tsb") {
    tab = "extra";
  }
  if (showTypeArr.value.includes(tab)) {
    packageType.value = tab;
  } else {
    packageType.value = showTypeArr.value[0] || "";
  }
}
function couponChange({ coupon_id, amount }: { coupon_id: number, amount: number }) {
  vipCurCoupon.value.coupon_id = coupon_id;
  vipCurCoupon.value.amount = amount;
}
function selectProductByCoupon(couponInfo: any) {
  const { threshold } = couponInfo;
  let info: any, infoIdx: number = 0;
  products.value.forEach((it, i) => {
    const price = it._actPrice * 100;
    if (price >= threshold) {
      if (!info) {
        info = it;
        infoIdx = i;
      } else if (info._actPrice < it._actPrice) {
        info = it;
        infoIdx = i;
      }
    }
  });
  if (info) {
    setVipItem(info, infoIdx);
    nextTick(() => {
      couponListRef.value?.handleCouponChange(couponInfo);
    });
  }
}
function canRefreshCouponByCoupon({ name }: {name: string}) {
  PsMessage({
    message: name + "已失效",
    customClass: "dialog-offset"
  });
  timer2 && clearTimeout(timer2);
  timer2 = setTimeout(() => {
    if (!payCodeRef.value?.confirmTips) {
      couponListRef.value?.getCouponListDb();
    }
  }, 3000) as unknown as number;
}
// 获取会员套餐列表
function getPackage() {
  vipListLoaded.value = true;
  const pkg_id = appInfo.value.allPackages[0];
  const params = { pkg_id };
  getProducts(params)
    .then((res) => {
      if (params.pkg_id !== appInfo.value.allPackages[0]) return;

      const data = res.data || {};
      let loopArr = data.list || []

      if (isSllMerchant.value) {
        loopArr = loopArr.filter((i: any) => !i.cycle_pay_flag)
      }
      products.value = loopArr.map((item: any) => {
        // 低至
        item.productDecs = computed(() => {
          return productDecs(
            item,
            actByProductMap.value[item.id],
            userInfo.value.has_buy,
            moneySymbol.value
          );
        });
        // 期限
        item.extText = extText(item.bus_ext.duration, item.unlimited);
        // 活动价格（不包含优惠券）
        item._actPrice = computed(() => {
          return formatActPrice(
            item,
            actByProductMap.value[item.id],
            userInfo.value.has_buy
          );
        });
        if (item.cycle_pay_flag) {
          // 周期付款价
          item._cycle_pay_period_price = formatMoney(
            item.cycle_pay_period_price
          );

          // 周期付款下周期文案
          item._next_cycle_pay_text = extCycleText(
            item.bus_ext.duration,
            item.bus_ext.cycle_pay_duration,
            item._cycle_pay_period_price
          );
        }
        // 原价
        item._origin_price = formatMoney(item.origin_price);
        // 优惠券最高抵扣金额
        item._coupon_price = computed(() => {
          const price = item._actPrice.value * 100;
          const coupon = vipCouponList.value.find(
            ({ threshold }) => threshold <= price
          );
          if (coupon?.amount) {
            return formatMoney(coupon.amount);
          }
          return "";
        });
        return item;
      });

      setVipItem(products.value[0] || {});
    })
    .catch(() => {
      if (params.pkg_id !== appInfo.value.allPackages[0]) return;

      products.value = [];

      setVipItem({});
    });
}
// 获取加购包列表
function getExtraPackageList() {
  extraListLoaded.value = true;
  const params = { product_type: 6, size: 10 };
  getExtraPackage(params).then((res: any) => {
    const data: any = res.data || {}
    extraList.value = (data.list || []).map((item: any) => {
      // 低至
      item.extraDecs = computed(() => {
        return extraDecs(
          item,
          actByProductMap.value[item.id],
          userInfo.value.has_buy,
          moneySymbol.value
        );
      });
      // 有效时间
      item.extraTime = extraTime(item);
      // 商品名
      item.extraName = extraName(item);
      // 活动价格（不包含优惠券）
      item._actPrice = computed(() => {
        return formatActPrice(
          item,
          actByProductMap.value[item.id],
          userInfo.value.has_buy
        );
      });
      // 原价
      item._origin_price = formatMoney(item.origin_price);
      return item;
    });
    selectedExtra.value = extraList.value[0] || {};
  });
}
// 获取商品角标
function getProductTags() {
  requestConfig("spjb", { isCache: false }).then((res: any) => {
    const list = res.params;
    if (!Array.isArray(list)) return;
    const o: any = {};
    for (const { product_id, img } of list) {
      if (product_id && img) {
        o[product_id] = img;
      }
    }
    productTagMap.value = o;
  });
}
// 转换会员套餐-期限
function extText(duration: number, unlimited: boolean) {
  if (unlimited) {
    return "终身";
  }
  if (duration % (duration / 365 / 24 / 60) === 0) {
    return duration / 365 / 24 / 60 + "年";
  }
  if (duration % (duration / 30 / 24 / 60) === 0) {
    return duration / 30 / 24 / 60 + "个月";
  }
  if (duration % (duration / 24 / 60) === 0) {
    return duration / 24 / 60 + "天";
  }
  if (duration % (duration / 60) === 0) {
    return duration + "小时";
  }
  return duration + "分钟";
}
// 转换会员套餐-周期付款下周期文案
function extCycleText(duration: number, cycle_pay_duration: number, _cycle_pay_period_price: number) {
  const symbol = moneySymbol.value;
  // @ts-ignore
  const day = parseInt(duration / 24 / 60);
  const money = _cycle_pay_period_price;

  if (cycle_pay_duration && cycle_pay_duration !== duration) {
    switch (cycle_pay_duration) {
      case 43200:
        return `${day}天后按每月${symbol}${money}自动续费，可随时取消`;
      case 129600:
        return `${day}天后按每季${symbol}${money}自动续费，可随时取消`;
      case 525600:
        return `${day}天后按每年${symbol}${money}自动续费，可随时取消`;
      default:
        return "";
    }
  }
  switch (duration) {
    case 43200:
      return `次月起按每月${symbol}${money}自动续费，可随时取消`;
    case 129600:
      return `次季起按每季${symbol}${money}自动续费，可随时取消`;
    case 525600:
      return `次年起按每年${symbol}${money}自动续费，可随时取消`;
    default:
      return "";
  }
}
// 转换会员套餐-低至
function productDecs(item: any, actInfo: any, has_buy: boolean, symbol: string) {
  if (item.unlimited) {
    return "永久使用";
  }
  if (item.cycle_pay_flag) {
    const money = formatMoney(item.cycle_pay_period_price);
    if (
      item.bus_ext.cycle_pay_duration &&
      item.bus_ext.cycle_pay_duration !== item.bus_ext.duration
    ) {
      return `${item.bus_ext.duration / 24 / 60}天后续费${symbol}${money}`;
    }
    if (item.bus_ext.duration === 43200) {
      return `次月续费${symbol}${money}`;
    }
    if (item.bus_ext.duration === 129600) {
      return `次季续费${symbol}${money}`;
    }
    if (item.bus_ext.duration === 525600) {
      return `次年续费${symbol}${money}`;
    }
    return "";
  }
  const days = Math.round(item.bus_ext.duration / (24 * 60)) || 1;
  if (days < 31) {
    const dayly = formatActPrice(item, actInfo, has_buy) / days;
    return `低至${symbol}${parseFloat(dayly.toFixed(2))}/天`;
  } else {
    const month = Math.round(days / 30.5);
    const monthly = formatActPrice(item, actInfo, has_buy) / month;
    return `低至${symbol}${parseFloat(monthly.toFixed(2))}/月`;
  }
}
// 转换加购包-名称
function extraName(item: any) {
  return item.show_name;
}
// 转换加购包-低至
function extraDecs(item: any, actInfo: any, has_buy: boolean, symbol: string) {
  const price = formatActPrice(item, actInfo, has_buy);
  const tsb = item.related_item?.items?.[0]?.setting?.count || 0;
  let minTsb = 10000;
  let num = tsb;
  if (num > minTsb) {
    num = num / minTsb;
  } else if (num >= 10) {
    minTsb = Number(1 + num.toString().slice(2));
    num = num / minTsb;
  } else {
    minTsb = num;
  }
  const text = formatTsb(minTsb);
  const price2 = parseFloat((price / num).toFixed(2));
  return `低至${symbol}${price2}/${text}翻译币`;
}
// 转换加购包-有效期
function extraTime(item: any) {
  if (item.unlimited) {
    return "永久有效";
  }
  const days = Math.round(item.bus_ext.duration / (24 * 60)) || 1;
  if (days < 31) {
    return `${days}天内有效`;
  } else {
    const month = Math.round(days / 30.5);
    if (month % 12) {
      return `${month}个月内有效`;
    } else {
      return `${month}年内有效`;
    }
  }
}
// 选择会员套餐
function setVipItem(item: any, i?: number) {
  selectedVip.value = item;
  typeof i === "number" &&
    nextTick(() => {
      $productSwiper?.slideTo(i);
    });
}
// 选择加购包商品
function setExtraItem(item: any, i?: number) {
  selectedExtra.value = item;
  typeof i === "number" &&
    nextTick(() => {
      $extraSwiper?.slideTo(i);
    });
}

// 匿名购买成功
const isAnonymous = computed(() => {
  if (!(isLxMerchant.value || isSllMerchant.value)) {
    return false
  }

  return !userInfo.value.PhoneNumber && !userInfo.value.HasBindWx
})

// 支付状态变更
function onPayChange(status: string) {
  if (status === "succes") {
    if (packageType.value === "extra") {
      if (isAnonymous.value) {
        anonymousPaySuccessType.value = "tsb"
        anonymousPaySuccessVisible.value = true
      } else {
        paySuccessType.value = "tsb";
        paySuccessVisible.value = true;
      }

      // 刷新翻译币
      _userAppStore_.getTsbCount()
        .then(count => {
          invokeAPi("fq_NotifyWebMessageEx", "", JSON.stringify({
            "action": "tsb-change",
            "data": { type: "pay-success", count }
          }))
        });
    } else {
      if (isAnonymous.value) {
        anonymousPaySuccessType.value = userInfo.value.is_member ? "renewal" : "vip"
        anonymousPaySuccessVisible.value = true
      } else {
        paySuccessType.value = userInfo.value.is_member ? "renewal" : "vip";
        paySuccessVisible.value = true;
      }

      _userAppStore_.getUserInfo(true)
        .then((sourceData: any) => {
          invokeAPi("fq_NotifyWebMessageEx", "", JSON.stringify({
            "action": "member-change",
            "data": { type: "pay-success", info: sourceData.data }
          }))
          invokeAPi('fq_update_member_info', JSON.stringify(sourceData));
        });

      extraListLoaded.value = false;
      getPackage();

      // couponListRef.value?.getCouponList();

      // _userAppStore_.getMyCoupons();

      // eventBus.emit("updateUserCoupon"); 由fq_NotifyWebMessageEx代替
      invokeAPi("fq_NotifyWebMessageEx", "", JSON.stringify({action: "user-coupon-change"}))
    }
  }
}

// 打开登录
function openLogin() {
  _userAppStore_.openLogin();
}
</script>

<style lang="scss" scoped>
@import "@/styles/mixins";

.member-container {
  overflow: auto;
  flex: 1;
}
.member-package {
  height: 100%;
  display: flex;
  justify-content: space-between;
  :deep(.concise-right) {
    position: relative;
    flex: 0 0 220px;
  }
}

.price {
  font-size: 24px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  .mark {
    font-size: 14px;
  }
  .mark2 {
    font-size: 16px;
  }
}
.origin-price {
  text-decoration: line-through;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: var(--el-text-color-disabled);
  padding: 0 8px;
}
.member-wrap {
  flex: 0 0 670px;
  // padding: 0 15px;
  box-sizing: border-box;
  position: relative;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  .empty-status {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 376px;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.7);
  }
  .swiper-slide {
    padding: 8px 0 5px;
    height: auto;
  }
  .time-item {
    height: 100%;
    position: relative;
    width: 202px;
    display: flex;
    flex-direction: column;
    // align-items: center;
    min-height: 160px;
    background: #ffffff;
    border-radius: 10px;
    border: 1px solid rgba(var(--el-color-primary-rgb), 0.2);
    font-weight: 400;
    font-size: 14px;
    color: #7b4801;
    // margin: 8px 0 5px;
    box-sizing: border-box;
    cursor: pointer;
    &:hover {
      border-color: #7b4801;
    }
    &.checked {
      background: linear-gradient(180deg, #fff2d8 0%, #ffe3ac 100%);
      box-shadow: none;
      .give,
      .upper-coupon {
        background: linear-gradient(180deg, #ffc045 0%, #ff3571 100%);
        color: #fff;
        em {
          background: unset;
          background-clip: unset;
          -webkit-text-fill-color: unset;
        }
      }
    }
    .item-cont {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 4px;
    }
    .time {
      font-size: 12px;
      margin-top: 12px;
      color: rgba(123, 72, 1, 0.7);
    }
    .item-name {
      padding-top: 20px;
      font-size: 14px;
      margin-bottom: 5px;
    }
    .origin-price {
      font-weight: 400;
      font-size: 12px;
      color: rgba(123, 72, 1, 0.5);
    }
    .monthly-price {
      font-size: 12px;
      min-width: 110px;
      padding: 2px 10px;
      line-height: 20px;
      background: rgba(123, 72, 1, 0.1);
      border-radius: 20px;
      color: #7b4801;
      text-align: center;
      margin: 8px auto;
    }
    .give,
    .upper-coupon {
      flex-grow: 0;
      min-height: 36px;
      border-radius: 0 0 10px 10px;
      background: linear-gradient(
        180deg,
        rgba(255, 192, 69, 0.1) 0%,
        rgba(255, 53, 113, 0.1) 100%
      );
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      padding: 2px 6px;
      box-sizing: border-box;
      em {
        font-weight: bold;
        background: linear-gradient(180deg, #ffc045 0%, #ff3571 100%);
        -webkit-background-clip: text;
        background-clip: text;
        -webkit-text-fill-color: transparent;
      }
      span {
        margin-left: 10px;
      }
      &.top {
        font-size: 14px;
        border-radius: 10px 10px 0 0;
        line-height: 14px;
        + .item-cont {
          padding-top: 14px;
          // padding-bottom: 14px;
        }
      }
    }
    .upper-coupon {
      min-height: 30px;
      background: linear-gradient(
        180deg,
        rgba(255, 192, 69, 0.1) 0%,
        rgba(255, 53, 113, 0.1) 100%
      );
    }
  }
}
.product-nav {
  flex: 0 0 47px;
  display: flex;
  align-items: flex-end;
  position: relative;
  .product-nav-item {
    flex: 1;
    text-align: center;
    font-size: 14px;
    color: #fff;
    cursor: pointer;
    line-height: 39px;
    position: relative;
    z-index: 1;
  }
  .product-nav-bg {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    &:before,
    &:after {
      content: "";
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
    }
    &:before {
      height: 39px;
      border-radius: 10px 10px 0 0;
      background: var(--el-color-primary);
    }
    &:after {
      top: 0;
      background-image: url("~@/assets/images/pay/center-pay-nav-1.png");
      background-size: 670px 47px;
      // background-repeat: no-repeat;
    }
  }

  &.extra .product-nav-bg:after {
    background-image: url("~@/assets/images/pay/center-pay-nav-2.png");
    background-position: right bottom;
  }
  &.vip .item-vip,
  &.extra .item-extra {
    font-weight: bold;
    font-size: 16px;
    line-height: 22px;
    align-self: center;
    color: var(--el-color-primary);
    // background-image: linear-gradient(
    //   to bottom,
    //   rgba(var(--el-color-regular-rgb), 1),
    //   rgba(var(--el-color-primary-rgb), 1)
    // );
    // -webkit-background-clip: text;
    // background-clip: text;
    // -webkit-text-fill-color: transparent;
  }
  &.vip .item-extra:hover,
  &.extra .item-vip:hover {
    ~ .product-nav-bg:before {
      @include colorOpa(background, var(--el-color-primary-rgb), 0.9);
    }
  }

  &.leng1 {
    flex: 0 0 48px;
    .product-nav-item:nth-child(2),
    .product-nav-bg:after {
      display: none;
    }
    .product-nav-item:nth-child(1) {
      color: #fff;
      line-height: 48px;
      cursor: default;
    }
    .product-nav-bg::before {
      height: 100%;
    }

    + .member-cont {
      padding-top: 10px;
    }

    .item-vip,
    .item-extra {
      -webkit-text-fill-color: initial !important;
    }
  }
}
.member-cont {
  flex: 1;
  background: linear-gradient(180deg, #f6f0ff, #ffffff); //#test
  // background: linear-gradient(180deg, #ecf3fe, #fff);
  border-radius: 0 0 10px 10px;
  position: relative;
  &:before {
    content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: linear-gradient(
      180deg,
      var(--el-color-primary),
      var(--el-color-primary-light-9)
    );
    -webkit-mask:
      linear-gradient(#fff 0 0) content-box,
      linear-gradient(#fff 0 0);
    mask:
      linear-gradient(#fff 0 0) content-box,
      linear-gradient(#fff 0 0);
    -webkit-mask-composite: xor;
    -webkit-mask-composite: exclude;
    mask-composite: exclude;
    padding: 0 1px 1px;
    border-radius: 0 0 10px 10px;
  }

  .member-cont_ {
    position: relative;
    z-index: 1;
    padding: 0 15px 14px;
  }
}
.product-swiper {
  position: relative;
  padding: 0 5px;
  margin: 0 -5px;
}
.ps-swiper-prev,
.ps-swiper-next {
  position: absolute;
  top: 50%;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
  border: 1px solid rgba(255, 255, 255, 0.5);
  color: #fff;
  z-index: 9;
  transition: opacity 0.25s ease;
  background: rgba(0, 0, 0, 0.5);
  font-size: 18px;
  cursor: pointer;
  .svg-icon {
    vertical-align: -0.08em;
  }
  &:hover {
    background: rgba(0, 0, 0, 0.6);
  }
  &.swiper-button-disabled {
    opacity: 0;
    pointer-events: none;
  }
}
.ps-swiper-prev {
  left: 0;
  transform: translate(0, -50%) rotate(180deg);
}
.ps-swiper-next {
  right: 0;
  transform: translate(0, -50%);
}

.pay-way {
  min-width: 170px;
  text-align: center;
  margin-right: 10px;
  margin-left: 45px;
  .svg-icon {
    font-size: 16px;
    vertical-align: -0.23em;
  }
}

.member-order {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: rgba(51, 51, 51, 0.03);
  border-radius: 10px;
  padding: 16px 20px;
  .detail-wrap {
    // height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .pay-code-wrap {
    overflow: hidden;
    margin: 0 auto;
  }
  .pay-money {
    flex: 1;
    color: var(--el-text-color-primary);
    padding: 0 10px;
    .price {
      position: relative;
      top: 10px;
      color: rgba(241, 88, 85, 1);
      font-size: 44px;
      .mark2 {
        font-size: 26px;
        vertical-align: middle;
      }
      .save-money {
        position: absolute;
        left: 100%;
        top: 0;
        padding: 0 10px;
        background: linear-gradient(90deg, #ffae00 0%, #ff6c8f 100%);
        border-radius: 5px 5px 5px 0px;
        font-size: 12px;
        height: 22px;
        line-height: 22px;
        color: #fff;
        font-weight: bold;
        white-space: nowrap;
      }
    }
  }
}

.agree-wrap {
  margin-top: 20px;
  font-size: 12px;
  line-height: 22px;
  text-align: center;
}
.agreement {
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
}

.lx-sale-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  column-gap: 3px;

  .tip-icon {
    cursor: pointer;
    margin-top: 1px;
    &:hover {
      color: var(--el-color-primary)
    }
  }
}

.custom-tag {
  position: absolute;
  right: -3px;
  top: -3px;
  width: 54px;
  height: 54px;
  background-size: 100% 100%;
}
.actually-paid {
  align-items: flex-end;
  justify-content: center;
  position: relative;
  .total-money {
    font-weight: 400;
    font-size: 14px;
    color: var(--el-text-color-primary);
  }
}
.countup-wrap {
  display: inline-block;
  font-family: Microsoft YaHei;
}
</style>
<style>
.number-spinner-enter-active,
.number-spinner-leave-active {
  display: inline-block;
  transition: all 0.3s ease;
}

.number-spinner-enter-from,
.number-spinner-leave-to {
  /* opacity: 0; */
  /* transform: translateY(-10px); */
  transform: scale(1.2);
}
</style>
